﻿using System;
using System.Data;
using System.IO;
using System.Windows.Forms;
using HRM.HRMServiceProxy;
using WeifenLuo.WinFormsUI.Docking;

namespace HRM
{
    public partial class frmSafetyDeviceList : DockContent
    {
        BranchClient _wcfBranch;
        DepartmentClient _wcfDepartment;
        SafetyDeviceClient _wcfSafetyDevice;
        int _month = DateTime.Now.Month;
        int _year = DateTime.Now.Year;
        int _SafetyDeviceID;
        int _BranchID;
        int _DepartmentID;
        int pageSize = UIParamater.pageSize;
        int currPage = 0;
        int itemCount = 0;
        int totalPage = 0;
        string _OrderBy = "";
        string _OrderDirection = "";

        RoleRightInfo listRole;

        public frmSafetyDeviceList()
        {

            InitializeComponent();
            this.KeyPreview = true;
            Language();
            _wcfSafetyDevice = Service.SafetyDevice();
            _wcfBranch = Service.Branch();
            _wcfDepartment = Service.Department();

            UISetting.LoadTreeView3(ref tvBranch);
            cboType.SelectedIndex = 0;
            listRole = UIParamater.Quyen_KhenThuong;
            if (!listRole._create)
                btnNew.Enabled = false;
            if (!listRole._update)
                btnDelete.Enabled = false;
            if (!listRole.Update)
            {
                this.btnEdit.Image = Properties.Resources.app;
                this.btnEdit.Tag = "Xem";
            }
        }

        private void Language()
        {
            if (this.Tag != null)
                this.TabText = this.Text = UpdateUI.GetString(this.Tag.ToString());
            UpdateUI.Load_ToolStrip(ref toolStrip1);
        }

        private void tvBranch_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Level == 0)
            {
                if (Program.isAdmin || Program.isViewAll)
                    _BranchID = 0;
                else
                    _BranchID = Program.intBranchID;
                _DepartmentID = 0;
                LoadData();

            }
            else if (e.Node.Level == 1)
            {
                _BranchID = Convert.ToInt32(e.Node.Tag);
                _DepartmentID = 0;
                currPage = 0;
                LoadData();

            }
            else if (e.Node.Level >= 2)
            {
                _DepartmentID = Convert.ToInt32(e.Node.Tag);
                _BranchID = 0;
                currPage = 0;
                LoadData();

            }
        }

        private void AddColums()
        {
            UISetting.AddColumn(ref dgvList, "RowNumber", "", "C", 40, true, true);
            UISetting.AddColumn(ref dgvList, "SafetyDevice_ID", "", "", 1, false, true);
            UISetting.AddColumn(ref dgvList, "SafetyDevice_Date", "", "C", 110, true, true);
            UISetting.AddColumn(ref dgvList, "Employee_FullName", "", "", 150, true, true);
            UISetting.AddColumn(ref dgvList, "SafetyDevice_Name", "", "", 200, true, true);
            UISetting.AddColumn(ref dgvList, "SafetyDevice_Status", "", "", 200, true, true);
            UISetting.AddColumn(ref dgvList, "SafetyDevice_No", "", "L", 200, true, true);
        }


        private void LoadData()
        {
            // int temptYear;
            //if (Int32.TryParse(cboYear.Text, out temptYear))
            //  _year = temptYear;

            string _keyword = UISetting.GetKeyWord(txtKeyWord.Text);
            string _type = cboType.Text.Trim();

            DataSet ds = _wcfSafetyDevice.SafetyDevice_GetList(out itemCount, _BranchID, _DepartmentID, _keyword, _type, _OrderBy, _OrderDirection, currPage, pageSize);

            totalPage = itemCount % pageSize > 0 ? (itemCount / pageSize) + 1 : (itemCount / pageSize);
            if (totalPage == 0)
                lblPageIndex.Text = "0" + "/" + totalPage.ToString();
            else
                lblPageIndex.Text = (currPage + 1).ToString() + "/" + totalPage.ToString();

            dgvList.Rows.Clear();
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                dgvList.Rows.Insert(i, 1);
                dgvList.Rows[i].Cells["RowNumber"].Value = ds.Tables[0].Rows[i]["RowNumber"].ToString();
                dgvList.Rows[i].Cells["SafetyDevice_ID"].Value = ds.Tables[0].Rows[i]["SafetyDevice_ID"].ToString();
                if (ds.Tables[0].Rows[i]["SafetyDevice_Date"] != DBNull.Value)
                    dgvList.Rows[i].Cells["SafetyDevice_Date"].Value = Convert.ToDateTime(ds.Tables[0].Rows[i]["SafetyDevice_Date"]).ToString("dd/MM/yyyy");
                dgvList.Rows[i].Cells["Employee_FullName"].Value = ds.Tables[0].Rows[i]["Employee_FullName"].ToString();
                dgvList.Rows[i].Cells["SafetyDevice_Name"].Value = ds.Tables[0].Rows[i]["SafetyDevice_Name"].ToString();
                dgvList.Rows[i].Cells["SafetyDevice_Status"].Value = ds.Tables[0].Rows[i]["SafetyDevice_Status"].ToString();
                dgvList.Rows[i].Cells["SafetyDevice_No"].Value = ds.Tables[0].Rows[i]["SafetyDevice_No"].ToString();
            }
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            if (!listRole.Create)
            {
                MessageBox.Show(UpdateUI.GetString("khongcoquyenthemmoi"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            Form f = new frmSafetyDevice(0, 0, listRole);
            if (f.ShowDialog(this) == DialogResult.OK)
            {
                LoadData();
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (dgvList.SelectedRows.Count > 0)
            {
                if (listRole.Update || listRole.View)
                {

                    _SafetyDeviceID = Convert.ToInt32(dgvList.CurrentRow.Cells["SafetyDevice_ID"].Value);
                    Form f = new frmSafetyDevice(_SafetyDeviceID, 0, listRole);
                    if (f.ShowDialog(this) == DialogResult.OK)
                    {
                        LoadData();
                    }
                }
                else
                    MessageBox.Show(UpdateUI.GetString("khongcoquyenxem"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (dgvList.SelectedRows.Count > 0)
            {
                if (!listRole.Delete)
                {
                    MessageBox.Show(UpdateUI.GetString("khongcoquyenthemmoi"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                _SafetyDeviceID = Convert.ToInt32(dgvList.CurrentRow.Cells["SafetyDevice_ID"].Value);
                if (MessageBox.Show(UpdateUI.GetString("bancochacchanxoa"), UIParamater.TitleProject, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (_wcfSafetyDevice.SafetyDevice_Delete(_SafetyDeviceID))
                    {
                        Program.taskbarNotifier.Show(UIParamater.TitleProject, UpdateUI.GetString("xoathanhcong"), UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                        LoadData();
                    }
                    else
                    {
                        MessageBox.Show(UpdateUI.GetString("xoakhongthanhcong"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
        }

        private void btnFisrt_Click(object sender, EventArgs e)
        {
            currPage = 0;
            LoadData();
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            if (currPage > 0)
                currPage--;
            LoadData();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (totalPage > 0 && currPage < totalPage - 1)
                currPage++;
            LoadData();
        }

        private void btnLast_Click(object sender, EventArgs e)
        {

        }

        private void dgvList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
                btnEdit_Click(null, null);
        }

        private void frmSafetyDeviceList_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Escape:
                    this.Dispose();
                    this.Close();
                    break;
                case Keys.F2:
                    btnNew_Click(null, null);
                    break;
                case Keys.F3:
                    btnEdit_Click(null, null);
                    break;
                case Keys.Delete:
                    btnDel_Click(null, null);
                    break;
            }
        }

        private void btnFind_Click(object sender, EventArgs e)
        {
            currPage = 0;
            LoadData();
        }

        private void txtKeyWord_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btnFind_Click(null, null);
        }

        private void cboYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            currPage = 0;
            LoadData();
        }

        private void frmSafetyDeviceList_Activated(object sender, EventArgs e)
        {
            Language();
            if (dgvList.Columns.Count > 0)
            {
                dgvList.Columns["RowNumber"].HeaderText = UpdateUI.GetString("stt");
                dgvList.Columns["SafetyDevice_Date"].HeaderText = UpdateUI.GetString("ngaygiao");
                dgvList.Columns["SafetyDevice_Name"].HeaderText = UpdateUI.GetString("tenthietbi");
                dgvList.Columns["Employee_FullName"].HeaderText = UpdateUI.GetString("hovaten");
                dgvList.Columns["SafetyDevice_Status"].HeaderText = UpdateUI.GetString("trangthai");
                dgvList.Columns["SafetyDevice_No"].HeaderText = "Số lượng";
            }
        }

        private void frmSafetyDeviceList_FormClosing(object sender, FormClosingEventArgs e)
        {
            _wcfSafetyDevice.Close();
            _wcfBranch.Close();
            _wcfDepartment.Close();
        }

        private void cboType_SelectedIndexChanged(object sender, EventArgs e)
        {
            dgvList.Columns.Clear();
            AddColums();
            Language();
            if (dgvList.Columns.Count > 0)
            {
                dgvList.Columns["RowNumber"].HeaderText = UpdateUI.GetString("stt");
                dgvList.Columns["SafetyDevice_Date"].HeaderText = UpdateUI.GetString("ngaygiao");
                dgvList.Columns["SafetyDevice_Name"].HeaderText = UpdateUI.GetString("tenthietbi");
                dgvList.Columns["Employee_FullName"].HeaderText = UpdateUI.GetString("hovaten");
                dgvList.Columns["SafetyDevice_Status"].HeaderText = UpdateUI.GetString("trangthai");
                dgvList.Columns["SafetyDevice_No"].HeaderText = "Số lượng";
            }
            LoadData();
        }

        private void dgvList_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            _OrderBy = dgvList.SortedColumn.Name;
            switch (dgvList.SortOrder.ToString())
            {
                case "Ascending":
                    _OrderDirection = "ASC";
                    break;
                case "Descending":
                    _OrderDirection = "DESC";
                    break;
            }
            LoadData();
        }

        private void btnExcel_Click(object sender, EventArgs e)
        {
            string _fileName = "";
            string branchName = "";
            string departmentName = "";
            _fileName = "tmpTBLD.xls";
            //int _month = Convert.ToInt32(cboMonth.ComboBox.SelectedValue);
            //int _year = Convert.ToInt32(cboYear.Text);
            BranchClient wcfBranch = Service.Branch();
            DepartmentClient wcfDepartment = Service.Department();
            if (_BranchID > 0)
            {
                branchName = wcfBranch.Branch_GetInfo(_BranchID).Name;
            }

            if (_DepartmentID > 0)
            {
                departmentName = wcfDepartment.Department_GetInfo(_DepartmentID).Name;
            }
            try
            {
                DataSet ds = _wcfSafetyDevice.SafetyDevice_GetList(out itemCount, _BranchID, _DepartmentID, txtKeyWord.Text, cboType.Text, _OrderBy, _OrderDirection, currPage, pageSize);
                if (ds.Tables.Count > 0)
                {
                    ds.Tables[0].Columns.Remove("SafetyDevice_ID");
                    ds.Tables[0].Columns.Remove("SafetyDevice_EmployeeID");
                    ds.Tables[0].Columns.Remove("SafetyDevice_BranchID");
                    ds.Tables[0].Columns.Remove("SafetyDevice_DepartmentID");
                    ds.Tables[0].Columns.Remove("Branch_ID");
                    ds.Tables[0].Columns.Remove("Department_ID");
                    ds.Tables[0].Columns["Rownumber"].Caption = "STT";
                    ds.Tables[0].Columns["Employee_FullName"].Caption = "Họ và tên";
                    ds.Tables[0].Columns["SafetyDevice_Date"].Caption = "Ngày giao";
                    ds.Tables[0].Columns["SafetyDevice_Name"].Caption = "Tên thiết bị";
                    ds.Tables[0].Columns["SafetyDevice_Type"].Caption = "Loại thiết bị";
                    ds.Tables[0].Columns["SafetyDevice_Status"].Caption = "Trạng thái";
                    ds.Tables[0].Columns["SafetyDevice_No"].Caption = "Số lượng";

                    ReadExcelFile.exportToExcelForEmployeeList("DANH SÁCH THIẾT BỊ CÔNG CỤ LAO ĐỘNG GIAO NHÂN VIÊN", branchName, departmentName, ds, Path.GetTempPath() + "\\" + _fileName);

                    try
                    {
                        System.Diagnostics.Process.Start(Path.GetTempPath() + "\\" + _fileName);
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Không mở được File \n" + Path.GetTempPath() + "\\" + _fileName, "Thông báo");
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("File " + Path.GetTempPath() + "\\" + _fileName + " đang được mở bằng một ứng dụng khác.\nHãy chọn file khác!", "Thông báo");
            }
        }
    }
}
